package com.xunji.standard.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunji.standard.cache.CodeBookCache;
import com.xunji.standard.common.Constant;
import com.xunji.standard.entity.CodeBook;
import com.xunji.standard.mapper.CodeBookMapper;
import com.xunji.standard.service.CodeBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xuqiang_imyours
 * @Date: 2025/8/25 9:17
 * @Description:
 **/
@Service
@Slf4j
public class CodeBookServiceImpl extends ServiceImpl<CodeBookMapper, CodeBook> implements CodeBookService {
    @Override
    public List<CodeBook> getCodeBookList() {
        return this.baseMapper.selectList(null);
    }

    @Override
    public Page<CodeBook> pageQuery(Long current, Long size) {
        Page<CodeBook> page = new Page<>(current, size);
        //按密码升序排序
        QueryWrapper<CodeBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("password");
        return this.page(page, queryWrapper);
    }

    @Override
    public void updateCache() {
        List<CodeBook> codeBookList = getCodeBookList();
        if (codeBookList != null && !codeBookList.isEmpty()) {
            ArrayList<String> list = new ArrayList<>();
            for (CodeBook codeBook : codeBookList) {
                list.add(codeBook.getPassword());
            }
            log.info("码簿列表：{}", list);
            CodeBookCache.put(Constant.CODE_BOOK, list);
        } else if (CodeBookCache.contains(Constant.CODE_BOOK)) {
            // 缓存中存在码簿列表，则删除
            CodeBookCache.remove(Constant.CODE_BOOK);
        }
    }

    @Override
    public boolean checkPasswordExists(String password) {
        if (password == null || password.trim().isEmpty()) {
            return false;
        }

        // 使用QueryWrapper查询是否存在相同密码
        QueryWrapper<CodeBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("password", password);
        Long count = this.baseMapper.selectCount(queryWrapper);
        return count > 0;
    }
}
